package logic

import (
	"context"
	"time"

	"probe-users/internal/errorx"
	"probe-users/internal/svc"
	"probe-users/internal/utils"
	"probe-users/pb/users"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ChangePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewChangePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePasswordLogic {
	return &ChangePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ChangePasswordLogic) ChangePassword(in *users.ChangePasswordRequest) (*users.ChangePasswordResponse, error) {
	// 参数验证
	if err := l.validateChangePasswordParams(in); err != nil {
		return nil, err
	}

	// 解析Token
	claims, err := utils.ParseToken(in.Token, l.svcCtx.Config.JWTAuth.AccessSecret)
	if err != nil {
		return nil, err
	}

	// 查询用户
	user, err := l.svcCtx.UserModel.FindOne(claims.UserId)
	if err != nil {
		return nil, errors.Wrapf(err, "查询用户失败: %d", claims.UserId)
	}

	// 验证旧密码
	if !utils.CheckPassword(in.OldPassword, user.Password) {
		return nil, errorx.ErrInvalidPassword
	}

	// 加密新密码
	newPassword, err := utils.HashPassword(in.NewPassword)
	if err != nil {
		return nil, errors.Wrapf(err, "密码加密失败")
	}

	// 更新密码
	user.Password = newPassword
	user.UpdatedAt = time.Now()
	if err := l.svcCtx.UserModel.Update(user); err != nil {
		return nil, errors.Wrapf(err, "更新密码失败: %d", user.ID)
	}

	return &users.ChangePasswordResponse{
		Success: true,
	}, nil
}

func (l *ChangePasswordLogic) validateChangePasswordParams(in *users.ChangePasswordRequest) error {
	if in.Token == "" {
		return errorx.ErrTokenNotEmpty
	}
	if in.OldPassword == "" {
		return errorx.ErrOldPasswordNotEmpty
	}
	if in.NewPassword == "" {
		return errorx.ErrNewPasswordNotEmpty
	}
	if len(in.NewPassword) < 6 || len(in.NewPassword) > 32 {
		return errorx.ErrNewPasswordLengthInvalid
	}
	if in.OldPassword == in.NewPassword {
		return errorx.ErrNewPasswordSameAsOld
	}
	return nil
}
